/* eslint "react-hooks/exhaustive-deps": "off" */
import React, { useEffect, useState } from 'react'
import Pager from '../../components/Pager'
import StucentTable from '../../components/StucentTable'
import StudentSearch from '../../components/StudentSearch'
import { searchStudents } from '../../services/student'
import qs from 'query-string'
import { StudentComp } from '../../components/SudentPager'

/**
 * 获取地址参数，返回一个对象
 * 如果某些条件在缺失，使用默认值
 */
function getQuery(serach) {
    let query = qs.parse(serach)
    query = Object.assign({ page: 1, limit: 10, key: "", sex: -1 }, query)
    // @ts-ignore
    query.limit = +query.limit
    // @ts-ignore
    query.sex = +query.sex
    return query
}

function useResp(query) {
    const [resp, setResp] = useState({ cont: 0, datas: [] })
    useEffect(() => {
        searchStudents({
            limit: query.limit,
            page: query.page,
            key: query.key,
            sex: query.sex
        }).then(res => [
            setResp(res)
        ])
    }, [query.limit, query.page, query.key, query.sex])
    return resp
}

// 改变地址
function changeLocation(history, query) {
    history.push('?' + qs.stringify(query))
}

export default function Students(props) {
    const query = getQuery(props.location.search);
    const { datas, cont } = useResp(query);

    return (
        <div>
            <div>
                <p>react-redux</p>
                <StudentComp />
            </div>
            {/* <div>
                <p></p>
                <StudentSearch defaultValue={{ key: query.key, sex: query.sex }} onSearch={(cod) => {
                    const newQuery = { ...query, key: cod.key, sex: cod.sex, page: 1 }
                    changeLocation(props.history, newQuery)
                }} />
                <StucentTable stus={datas} />
                <Pager total={cont} current={+query.page} limit={query.limit} onPageChange={(i) => {
                    const newQuery = { ...query, page: i }
                    changeLocation(props.history, newQuery)
                }} />
            </div> */}

        </div>
    )
}
